package cn.acewill.yxd.yunxundian.ui.vdieogo;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;

import com.videogo.constant.Constant;
import com.videogo.constant.IntentConsts;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.adapter.EZPlayerListAdapter;
import cn.acewill.yxd.yunxundian.ui.vdieogo.scan.main.CaptureActivity;
import cn.acewill.yxd.yunxundian.ui.vdieogo.util.EZUtils;

import static cn.acewill.yxd.yunxundian.YXDAPP.getOpenSDK;

/**
 * Created by XXX on 2017/6/19.
 * @author xxx
 * 登录成功后展示用户的设备数据
 */

public class EZCameraListActivity extends AppCompatActivity{
    protected static final String TAG = "CameraListActivity";
    public final static int REQUEST_CODE = 100;
    public final static int RESULT_CODE = 101;

    private ImageView loginOut,addDevice;
    private Toolbar toolbar;
    private ListView myPlayList;
    private EZPlayerListAdapter adapter;
    private BroadcastReceiver mReceiver = null;
    //获取到的设备list
    private List<EZDeviceInfo> myDeviceList;
    //分享设备
    private List<EZDeviceInfo> shareDeviceList;
    //totalLit
    private List<EZDeviceInfo> totalList=new ArrayList<>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ezplaymain);
        initView();
        initData();
       new getAllList().execute();
    }

    public void initView(){
        this.toolbar= (Toolbar) findViewById(R.id.toolbar);
        this.loginOut= (ImageView) findViewById(R.id.loginOut);
        this.addDevice= (ImageView) findViewById(R.id.addDevice);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        myPlayList= (ListView) findViewById(R.id.myList);
        loginOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popLogoutDialog();
            }
        });
        addDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EZCameraListActivity.this, CaptureActivity.class);
                startActivity(intent);
            }
        });
    }

    public class getAllList extends AsyncTask<String,String,List<EZDeviceInfo>>{

        //拉取数据源
        @Override
        protected List<EZDeviceInfo> doInBackground(String... params) {

            try {
                myDeviceList = EZOpenSDK.getInstance().getDeviceList(0, 20);
                shareDeviceList=EZOpenSDK.getInstance().getSharedDeviceList(0,20);
            } catch (BaseException e) {
                e.printStackTrace();
            }
            if (myDeviceList!=null){
                for (int i=0;i<myDeviceList.size();i++){
                    totalList.add(myDeviceList.get(i));
                }
            }
            if (shareDeviceList!=null){
                for (int i=0;i<shareDeviceList.size();i++){
                    totalList.add(shareDeviceList.get(i));
                }
            }
            return totalList;
        }

        //设置适配器
        @Override
        protected void onPostExecute(List<EZDeviceInfo> ezDeviceInfos) {
            super.onPostExecute(ezDeviceInfos);
            adapter=new EZPlayerListAdapter(EZCameraListActivity.this, ezDeviceInfos, new EZPlayerListAdapter.ViewOnClick() {
                @Override
                public void toPlayVideo(int position) {
                    //跳转播放界面
                    EZDeviceInfo deviceInfo = (EZDeviceInfo) adapter.getItem(position);
                    EZCameraInfo cameraInfo = EZUtils.getCameraInfoFromDevice(deviceInfo, 0);
                    Intent in=new Intent();
                    in.setClass(EZCameraListActivity.this,EZRealPlayActivity.class);
                    in.putExtra(IntentConsts.EXTRA_CAMERA_INFO, cameraInfo);
                    in.putExtra(IntentConsts.EXTRA_DEVICE_INFO, deviceInfo);
                    startActivityForResult(in,REQUEST_CODE);
                }
            });
            myPlayList.setAdapter(adapter);
        }

    }

    private class LogoutTask extends AsyncTask<Void, Void, Void> {
        private Dialog mWaitDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mWaitDialog = new WaitDialog(EZCameraListActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
            mWaitDialog.setCancelable(false);
            mWaitDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            getOpenSDK().logout();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mWaitDialog.dismiss();
            ActivityUtils.goToLoginAgain(EZCameraListActivity.this);
            finish();
        }
    }
    private void popLogoutDialog() {
        AlertDialog.Builder exitDialog = new AlertDialog.Builder(EZCameraListActivity.this);
        exitDialog.setTitle(R.string.exit);
        exitDialog.setMessage(R.string.exit_tip);
        exitDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new LogoutTask().execute();
            }
        });
        exitDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        exitDialog.show();
    }

    //添加设备的广播
    public void initData(){
        mReceiver =new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                LogUtil.debugLog(TAG, "onReceive:" + action);
                if (action.equals(Constant.ADD_DEVICE_SUCCESS_ACTION)) {
                    //刷新数据列表
                    new getAllList().execute();
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ADD_DEVICE_SUCCESS_ACTION);
        registerReceiver(mReceiver, filter);
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_CODE){
            if (requestCode == REQUEST_CODE){
                String deviceSerial = intent.getStringExtra(IntentConsts.EXTRA_DEVICE_ID);
                int cameraNo = intent.getIntExtra(IntentConsts.EXTRA_CAMERA_NO,-1);
                int videoLevel = intent.getIntExtra("video_level",-1);
                if (TextUtils.isEmpty(deviceSerial)){
                    return;
                }
                if (videoLevel == -1 || cameraNo == -1){
                    return;
                }
                if (adapter.getDeviceInfoList() != null){
                    for (EZDeviceInfo deviceInfo:adapter.getDeviceInfoList()){
                        if (deviceInfo.getDeviceSerial().equals(deviceSerial)){
                            if (deviceInfo.getCameraInfoList() != null){
                                for (EZCameraInfo cameraInfo:deviceInfo.getCameraInfoList()){
                                    if (cameraInfo.getCameraNo() == cameraNo){
                                        cameraInfo.setVideoLevel(videoLevel);
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }
}
